<script setup lang="ts">
import useUserStore from "@/store/modules/useUserStore";
import useBiliStore from "@/store/modules/useBiliStore";
import { useThrottleFn } from "@vueuse/core";
import $api from "@/api";

const userStore = useUserStore(),
  biliStore = useBiliStore(),
  router = useRouter();
const showLogin = ref(false),
  showAuth = ref(false),
  roomStatus = ref(0);
const options = [
  {
    label: "个人中心",
    key: "user"
  },
  {
    label: "退出登录",
    key: "logout"
  }
];
onBeforeUnmount(() => {
  window.$bus.off("blive:Close", onBLiveClose);
  window.$bus.off("blive:Open", onBLiveOpen);
  window.$bus.off("blive:Error", onBLiveError);
});
init();

function logout() {
  userStore.clear();
}
function handleSelect(key) {
  switch (key) {
    case "user":
      router.replace("/user");
      break;
    case "logout":
      logout();
      break;
  }
}
function onBLiveClose(event, value) {
  console.log("closeBlive");
  roomStatus.value = 0;
}
function onBLiveOpen() {
  roomStatus.value = 1;
}
function onBLiveError() {
  roomStatus.value = -1;
}
function init() {
  $api.bili.getBaseUserInfo();
  window.$bus.on("blive:Close", onBLiveClose);
  window.$bus.on("blive:Open", onBLiveOpen);
  window.$bus.on("blive:Error", onBLiveError);
  startBiliCode();
}
function startBiliCode() {
  window.electronAPI.getExecArgs("code").then(val => {
    if (!val) return;
    biliStore.code = val;
    $api.bili
      .startBiliApp()
      .then(data => {
        $api.bili.heartBiliApp();
      })
      .catch(err => {
        showAuth.value = true;
      });
  });
}
const starRoomLive = useThrottleFn(() => {
  if (!biliStore.roomId) return window.$message.error("直播间号必填");
  window.electronAPI.listenBlive(+biliStore.roomId);
}, 2000);
const stopRoomLive = useThrottleFn(() => {
  window.electronAPI.stopBlive();
}, 2000);
</script>

<template>
  <div class="flex-ec">
    <n-button
      class="mr-4"
      type="primary"
      strong
      secondary
      @click="showAuth = true"
      >身份码</n-button
    >
    <div class="flex-sc mr-4">
      <n-input
        v-model:value="biliStore.roomId"
        placeholder="请输入直播间号"
        :disabled="roomStatus == 1"
        style="width: 150px"
      />
      <n-button
        v-if="roomStatus == 1"
        type="warning"
        strong
        secondary
        @click="stopRoomLive"
        >关闭</n-button
      >
      <n-button v-else type="primary" @click="starRoomLive">监听</n-button>
    </div>
    <template v-if="userStore.hasLogin">
      <n-dropdown :options="options" :show-arrow="true" @select="handleSelect">
        <img
          class="w-10 h-10 rounded-full bg-light-100"
          :src="userStore.user?.face"
        />
      </n-dropdown>
    </template>
    <template v-else>
      <n-button type="primary" @click="showLogin = true">登录</n-button>
    </template>
  </div>
  <MLogin v-model:show="showLogin" />
  <MBiliAuth v-model:show="showAuth" />
</template>

<style scoped lang="scss"></style>
